/**
 * Copyright (c) 2018, wuyy All rights reserved.
 * wuyy 专有/保密源代码,未经许可禁止任何人通过任何渠道使用、修改源代码.
 * QQ:16349023
 * 项目名称 : com.wy2.eclipse.tool.lib
 * @version V1.0
 */
package com.wy2.eclipse.tool.lib;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.wy2.core.PropertiesDocument;
import com.wy2.core.common.EncodingConsts;
import com.wy2.core.date.DateTime;
import com.wy2.core.tool.JsonTools;
import com.wy2.eclipse.tool.lib.common.Constants;
import com.wy2.eclipse.tool.lib.common.IDEUtils;
import com.wy2.eclipse.tool.lib.entity.CodeGenerateInfo;
import com.wy2.eclipse.tool.lib.entity.TableModuleConfig;
import com.wy2.generator.database.common.DatabaseMetaDataEntity;

/**
 * 项目配置管理器
 * @author wuyy<16349023@qq.com>
 * @date 2018年1月27日上午10:13:41
 * 
 */
public class ProjectConfigManager {
    
    private static final Logger logger=LoggerFactory.getLogger(ProjectConfigManager.class);

    private final IProject project;
    private final String generateConfigRelativePath;

    public ProjectConfigManager(IProject project,String generateConfigRelativePath) {
        super();
        this.project = project;
        this.generateConfigRelativePath=generateConfigRelativePath;
    }

    public IProject getProject() {
        return project;
    }
    
    /**
     * 返回生成信息保存目录
     * @return
     */
    public File getGenerateInfoDirectory() {
        if(project!=null) {
            File generateDirectory=new File(getProject().getLocation().toOSString(), Constants.GENERATE_DIRECTORY);
            return generateDirectory;
        }
        return null;
        
        
    }
    /**
     * 返回代码生成时，数据库元数据缓存文件
     * @return
     */
    public File getDatabaseMetaDataFile() {
        if(project!=null) {
            File dbMetaDataFile=new File(getGenerateInfoDirectory(), Constants.GENERATE_METADATA_FILE);
            return dbMetaDataFile;
        }
        return null;
        
    }
    
    /**
     * 返回代码生成时，数据表模块配置文件
     * @return
     */
    public File getTableModuleConfigFile() {
        if(project!=null) {
            File dbMetaDataFile=new File(getGenerateInfoDirectory(), Constants.GENERATE_METADATA_MODULE_FILE);
            return dbMetaDataFile;
        }
        return null;
        
    }
    /**
     * 返回代码生成信息文件
     * @return
     */
    public File getCodeGenerateInfoFile() {
        if(project!=null) {
            File dbMetaDataFile=new File(getGenerateInfoDirectory(), Constants.GENERATE_CODE_INFO_FILE);
            return dbMetaDataFile;
        }
        return null;
        
    }
    
    /**
     * 返回生成配置文件
     * @param generateConfigFileRelativePath
     * @return
     */
    public File getGenerateConfigFile() {
        if(project!=null) {
            String projectPath=project.getLocation().toOSString();
            File configFile=new File(projectPath, generateConfigRelativePath);
            return configFile;
        }
        return null;
    }
    
    
    public Boolean isExistDatabaseMetaDataFile() {
        return getDatabaseMetaDataFile().exists();
    }
    public DatabaseMetaDataEntity loadDatabaseMetaData(Boolean reload){
        DatabaseMetaDataEntity databaseMetaDataEntity =null;
        File dbMetaDataFile=getDatabaseMetaDataFile();
        if(!reload && isExistDatabaseMetaDataFile()) {
            try {
                databaseMetaDataEntity=JsonTools.read(dbMetaDataFile, EncodingConsts.UTF_8, DatabaseMetaDataEntity.class);
                
            } catch (Exception e) {
                logger.error("读取数据库元数据异常", e);
            }
        }
        return databaseMetaDataEntity;
    }
    
    public void saveDatabaseMetaData(DatabaseMetaDataEntity databaseMetaDataEntity) {
        try {
            if(databaseMetaDataEntity!=null || !databaseMetaDataEntity.getTables().isEmpty() || databaseMetaDataEntity.getTables().size() > 0) {
                JsonTools.save(databaseMetaDataEntity, true, getDatabaseMetaDataFile(), EncodingConsts.UTF_8);
                IDEUtils.refreshProject(getProject());
            }
            
        } catch (Exception e) {
            logger.error("写入数据库元数据异常", e);
        } 
    }
    
    public Boolean isExistTableModuleConfigFile() {
        return getTableModuleConfigFile().exists();
    }
    public TableModuleConfig loadTableModuleConfig() {
        TableModuleConfig moduleConfig=null;
        if(isExistTableModuleConfigFile()) {
            try {
                moduleConfig = JsonTools.read(getTableModuleConfigFile(), EncodingConsts.UTF_8, TableModuleConfig.class);
            } catch (Exception e) {
                logger.error("读取数据库表的模块数据异常", e);
            }
        }        
        return moduleConfig;
    }
    
    public void saveTableModuleConfig(TableModuleConfig moduleConfig) {
        try {
            moduleConfig.setUpdateDate(DateTime.Now().toString());
            JsonTools.save(moduleConfig, true, getTableModuleConfigFile(), EncodingConsts.UTF_8);
            IDEUtils.refreshProject(getProject());
        } catch (Exception e) {
            logger.error("保存模块信息异常", e);
        }
    }
    
    
    public Boolean isExistCodeGenerateInfoFile() {
        return getCodeGenerateInfoFile().exists();
    }
    
    /**
     * 返回代码生成信息
     * @return
     */
    public CodeGenerateInfo loadCodeGenerateInfo() {
        CodeGenerateInfo codeGenerateInfo =null;
        if(isExistCodeGenerateInfoFile()) {
            try {
                codeGenerateInfo=JsonTools.read(getCodeGenerateInfoFile(), EncodingConsts.UTF_8, CodeGenerateInfo.class);
            } catch (Exception e) {
                logger.error("读取代码生成信息异常", e);
            }
        }
        return codeGenerateInfo;
    }
    public void saveCodeGenerateInfo(CodeGenerateInfo codeGenerateInfo) {
        try {
            JsonTools.save(codeGenerateInfo, true, getCodeGenerateInfoFile(), EncodingConsts.UTF_8);
            IDEUtils.refreshProject(getProject());
        } catch (Exception e) {
            logger.error("保存模块信息异常", e);
        }
    }
    
    public Boolean existGenerateConfigFile() {
        return getGenerateConfigFile().exists();
    }
    
    public PropertiesDocument loadGenerateConfig() {
        if(!existGenerateConfigFile()) {
            return null;
        }
        PropertiesDocument propertiesDocument=new PropertiesDocument(true);
        try {
            propertiesDocument.loadAndMerge(null, true, getGenerateConfigFile().getAbsolutePath());
        } catch (IOException e) {
            logger.error("加载代码生成配置信息异常", e);
            return null;
        }
        return propertiesDocument;
    }
    
    public void createGenerateConfig() {
        String configPath=Constants.CONFIG_TEMPLATE_DIRECTORY +"/"+Constants.GENERATE_CONFIG_NAME;
        Bundle uiBundle = Platform.getBundle("com.wy2.eclipse.tool.ui");
        if(uiBundle==null) {
            logger.error("无法找到生成配置的模板文件");
            return;
        }
        try(InputStream inputStream = uiBundle.getEntry(configPath).openStream();
                FileOutputStream fos = new FileOutputStream(getGenerateConfigFile())){
            for(byte[] buffer = new byte[1024 * 4];;) {
                int n = inputStream.read(buffer);
                if(n < 0) {
                  break;
                }
                fos.write(buffer, 0, n);
              }
            fos.flush();
            
            
            //IDEUtils.refreshFile(configFile.getAbsolutePath());
            logger.info("生成配置创建成功，位置： {}",getGenerateConfigFile());
        } catch (IOException e) {
            logger.error("创建生成配置异常", e);
        }
        IDEUtils.refreshProject(project);
    }
}
